const api = require('../../config/api.js')
const util = require('../../utils/util.js')

const app = getApp()

Page({
  data: {
    pie1Opts: {
      lazyLoad: true // 延迟加载组件
    },
    pie2Opts: {
      lazyLoad: true
    },
    userInfo:{},
    option1: [],
    option2: [],
    enterpriseId: '',
    placeId: '',
    date: '',
    calendarShow: false,
    canvasHidden: false,
    minDate: new Date(2022, 8, 1).getTime(),
    maxDate: new Date().getTime(),
    dayTime: new Date().getTime(),
    dateTime: '',
    ec: {
      lazyLoad: true
    },
    pie1Data:[],
    ec1: {
      lazyLoad: true
    },
    pie2Data: []
  },
  openMenu(){
    console.log('openMenu')
    this.setData({ canvasHidden: true })
  },
  closeMenu(){
    console.log('closeMenu')
    this.setData({ canvasHidden: false })
  },
  // 企业选择
  change1({detail}){
    const vm = this
    vm.setData({
      enterpriseId: detail,
      placeId: ''
    })
    wx.setStorage({
      key:"enterpriseId",
      data: detail
    })
    vm.getData()
  },
  // 场地选择
  change2({detail}){
    const vm = this
    vm.setData({
      placeId: detail
    })
    vm.getData()
  },
  // 更多1
  moreClick1(){
    const vm = this
    wx.navigateTo({
      url: '/pages/pdDetail/pdDetail?eId='+vm.data.enterpriseId+'&pId='+vm.data.placeId+'&date='+vm.data.date
    })
    // wx.showToast({
    //   title: '今日数据尚未更新，请耐心等待！',
    //   icon: 'none',
    //   duration: 2000
    // })
  },
  // 更多2
  moreClick2(){
    const vm = this
    wx.navigateTo({
      url: '/pages/fmDetail/fmDetail?eId='+vm.data.enterpriseId+'&pId='+vm.data.placeId+'&date='+vm.data.date,
    })
    // wx.showToast({
    //   title: '今日数据尚未更新，请耐心等待！',
    //   icon: 'none',
    //   duration: 2000
    // })
  },

  calendarDisplay() {
    const vm = this
    vm.setData({ 
      calendarShow: true,
      canvasHidden: true,
      dayTime: vm.data.dateTime.getTime()
    })
  },
  calendarClose() {
    this.setData({ 
      calendarShow: false,
      canvasHidden: false
    })
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
  },
  // 日期选择确认
  calendarConfirm(event) {
    const vm = this
    vm.setData({
      calendarShow: false,
      canvasHidden: false,
    });

    vm.setChoosedDate(event.detail)
    vm.getData()
  },
  // 后一天
  downClick(){
    const vm = this
    let dateTime = vm.data.dateTime
    let nowDate = new Date(new Date().setHours(0, 0, 0, 0))
    
    if(dateTime > nowDate){
      return
    }

    dateTime = dateTime.setDate(dateTime.getDate() + 1)
    dateTime = new Date(dateTime)
    
    vm.setChoosedDate(dateTime)
    vm.getData()
  },
  // 前一天
  upClick(){
    const vm = this
    let dateTime = vm.data.dateTime
    let _createDate = vm.data.userInfo.createDate
    if(app.globalData.isIos){
      _createDate = _createDate.replace(/-/g, "/")
    }
    let userCreateDate = new Date(_createDate)
    if(dateTime < userCreateDate){
      return
    }

    dateTime = dateTime.setDate(dateTime.getDate() - 1)
    dateTime = new Date(dateTime)
    
    vm.setChoosedDate(dateTime)
    vm.getData()
  },
  // 企业列表
  getOpt1(){
    const vm = this
    return new Promise(function(resolve, reject) {
      util.wxRequest({
        url: api.EnterpriseList,
        method: 'get',
        header:{},
        data: {},
        success: function (res) {
          let row = res.data
          let option1 = []
          row.data.enterpriseList.forEach(item => {
            option1.push({
              text: item.enterpriseName,
              value: item.enterpriseId
            })
          })
          vm.setData({
            option1: option1
          })
          resolve()
        },
        complete: () => {
          wx.hideLoading()
        }
      })
    })
  },
  // 场地列表
  getOpt2(){
    const vm = this
    return new Promise(function(resolve, reject) {
      util.wxRequest({
        url: api.PlaceList,
        method: 'get',
        header:{
          'content-type': 'application/json'
        },
        data: {
          enterpriseId: util.getStorageSync('enterpriseId')
        },
        success: function (res) {
          let row = res.data
          let option2 = []
          row.data.placeList.forEach(item => {
            option2.push({
              text: item.placeName,
              value: item.placeId
            })
          })
          vm.setData({
            option2: option2
          })
          resolve()
        },
        complete: () => {
          wx.hideLoading()
        }
      })
    })
    
  },

  initPie1(){
    const vm = this
    let pie1 = vm.selectComponent('#lazy-pie1')
    
    pie1.init((canvas, width, height, F2) => {
      var data = vm.data.pie1Data
      let total = 0;
      let dataDic = {}

      data.map(obj => {
        total += obj.value
        dataDic[obj.name] = obj.value
      })
      
      var chart = new F2.Chart({
        el: canvas,
        width,
        height
      });
      chart.source(data);

      // 图例
      chart.legend({
        position: 'right',
        itemFormatter(val) {
          return val + '  ' + dataDic[val]
        }
      });
      // 点击每一项之后的提示信息
      chart.tooltip(false)
      chart.coord('polar', {
        transposed: true,
        radius: 0.85,
        innerRadius: 0.618
      });
      chart.axis(false);
      chart
        .interval()
        // 占据的位置
        .position('a*value')
        // 颜色
        .color('name', ['#1890FF', '#13C2C2', '#2FC25B', '#FACC14', '#F04864', '#8543E0'])
        .adjust('stack')
        .style({
          lineWidth: 1,
          stroke: '#fff',
          lineJoin: 'round',
          lineCap: 'round'
        });
      
      // 中间
      chart.guide().text({
        position: ['50%', '50%'],
        content: total,
        style: {
          fontSize: 24
        }
      });
      chart.render();
      
      return chart;
    });
  },
  initPie2(){
    const vm = this
    let pie2 = vm.selectComponent('#lazy-pie2')
    
    pie2.init((canvas, width, height, F2) => {
      var data = vm.data.pie2Data
      let total = 0;
      let dataDic = {}

      data.map(obj => {
        total += obj.value
        dataDic[obj.name] = obj.value
      })
      
      var chart = new F2.Chart({
        el: canvas,
        width,
        height
      });
      chart.source(data);

      // 图例
      chart.legend({
        position: 'right',
        itemFormatter(val) {
          return val + '  ' + dataDic[val]
        }
      });
      // 点击每一项之后的提示信息
      chart.tooltip(false)
      chart.coord('polar', {
        transposed: true,
        radius: 0.85,
        innerRadius: 0.618
      });
      chart.axis(false);
      chart
        .interval()
        // 占据的位置
        .position('a*value')
        // 颜色
        .color('name', ['#1890FF', '#13C2C2', '#2FC25B', '#FACC14', '#F04864', '#8543E0'])
        .adjust('stack')
        .style({
          lineWidth: 1,
          stroke: '#fff',
          lineJoin: 'round',
          lineCap: 'round'
        });
      
      // 中间
      chart.guide().text({
        position: ['50%', '50%'],
        content: total,
        style: {
          fontSize: 24
        }
      });
      chart.render();
      
      return chart;
    });
  },
  
  // 首页数据
  getData(){
    const vm = this
    wx.showLoading({ title: '' })
    
    util.wxRequest({
      url: api.IndexData,
      method: 'get',
      header:{
        'content-type': 'application/json'
      },
      data: {
        enterpriseId: vm.data.enterpriseId,
        placeId: vm.data.placeId,
        date: vm.data.date
      },
      success: function (res) {
        let row = res.data
        
        row.data.enterpriseList.forEach(item => {
          item.text = item.enterpriseName
          item.value = item.enterpriseId
        })
        row.data.placeList.forEach(item => {
          item.text = item.placeName
          item.value = item.placeId
        })
        vm.setData({
          option1: row.data.enterpriseList,
          option2: row.data.placeList
        })
        vm.setData({
          enterpriseId: row.data.enterpriseId,
          placeId: row.data.placeId
        })
        row.data.placeList.forEach(item => {
          if(item.placeId == row.data.placeId){
            wx.setStorageSync('placeName', item.placeName)
          }
        })
        row.data.enterpriseList.forEach(item => {
          if(item.enterpriseId == row.data.enterpriseId){
            wx.setStorageSync('enterpriseName', item.enterpriseName)
          }
        })
        
        wx.setStorageSync('enterpriseId', row.data.enterpriseId)
        wx.setStorageSync('placeId', row.data.placeId)
        
        vm.setData({
          pie1Data: row.data.typeCount,
          pie2Data: row.data.deliverCount
        })
        vm.data.pie1Data = row.data.typeCount
        vm.data.pie2Data = row.data.deliverCount
        
        if(vm.data.pie1Data && vm.data.pie1Data.length > 0){
          vm.initPie1()
        }
        
        if(vm.data.pie2Data && vm.data.pie2Data.length > 0){
          vm.initPie2()
        }
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  },
  // initUserPlace
  initUserPlace(){
    let vm = this
    return new Promise(function(resolve, reject) {
      vm.getOpt1().then(() => {
        vm.getOpt2().then(() => {
          resolve()
        })
      })
    })
  },
  initChoosedDate(){
    const vm = this
    let choosed_date = util.getStorageSync('choosed_date')
    if(util.isEmpty(choosed_date)){
      choosed_date = new Date()
    }
    vm.setData({
      // 字符串日期参数
      date: vm.formatDate(choosed_date),
      dateTime: choosed_date
    })
  },
  setChoosedDate(_date){
    const vm = this
    if(util.isEmpty(_date)){
      _date = new Date()
    }

    wx.setStorageSync('choosed_date', _date)
    vm.setData({
      // 字符串日期参数
      date: vm.formatDate(_date),
      dateTime: _date
    })
  },
  // onShow
  onShow(){
    const vm = this
    console.log('home page onShow')
    vm.initChoosedDate()

    app.getUserInfo(user => {
      
      vm.initUserPlace().then(() => {
        let _createDate = user.createDate
        if(app.globalData.isIos){
          _createDate = _createDate.replace(/-/g, "/")
        }

        vm.setData({
          // _createDate如果格式不对，ios会很慢很慢
          minDate: new Date(_createDate).getTime(),
          userInfo: user,
          enterpriseId: util.getStorageSync('enterpriseId'),
          placeId: util.getStorageSync('placeId')
        });
        vm.getData()
      })
    })
  },
})